Python 时间分析

import cProfile
import pstats
import os
# 性能分析装饰器定义
def do_cprofile(filename):
    def wrapper(func):
        def profiled_func(*args, **kwargs):
            # Flag for do profiling or not.
            DO_PROF = os.getenv("PROFILING")
            if DO_PROF:
                profile = cProfile.Profile()
                profile.enable()
                result = func(*args, **kwargs)
                profile.disable()
                # Sort stat by internal time.
                sortby = "tottime"
                ps = pstats.Stats(profile).sort_stats(sortby)
                ps.dump_stats(filename)
            else:
                result = func(*args, **kwargs)
            return result
        return profiled_func
    return wrapper
  
@do_cprofile('./main.prof')
main()
$ pip install gprof2dot
$ gprof2dot -f pstats main.prof | dot -Tpng -o main.png

gprof项目地址